﻿using System.Text.RegularExpressions;
using Microsoft.Security.Application;
using System.Web.UI.WebControls;
using System.Text;
using System.Web;
using System.IO;
using System;
using System.Collections.Generic;
using Entities;
using System.ComponentModel;

namespace Logic
{

    internal static class Validations
    {
        private static string CheckDigit(int rut)
        {
            int digit;
            int cont;
            int multiplier;
            int collector;
            string digitRut;

            cont = 2;
            collector = 0;

            while (rut != 0)
            {
                multiplier = (rut % 10) * cont;
                collector = collector + multiplier;
                rut = rut / 10;
                cont = cont + 1;
                if (cont == 8)
                {
                    cont = 2;
                }

            }

            digit = 11 - (collector % 11);
            digitRut = digit.ToString().Trim();
            if (digit == 10)
            {
                digitRut = "K";
            }
            if (digit == 11)
            {
                digitRut = "0";
            }
            return (digitRut);
        }

        public static bool ValidateRol(this List<Rol> roles)
        {
            bool response = true;
            foreach (Rol r in roles)
            {
                if (!r.id.IsNumber() || !r.description.ValidateText(50))
                {
                    response = false;
                    break;
                }
            }
            return response;
        }

        public static T CleanParameter<T>(this T data)
        {
            if (data != null)
            {
                object temp = data;
                temp = AntiXss.GetSafeHtmlFragment(data.ToString());
                temp = Regex.Replace(data.ToString(), @"(&|DROP|ALTER|TRUNCATE|SELECT|FROM|WHERE|UPDATE|DELETE|CREATE|SHUTDOWN|LIKE|UNION|;|'|%|#|DB_|CAST|CONVERT|KILL|OPEN|TABLE|EXEC|FECTH|)", "", RegexOptions.IgnoreCase);
                //brigido..no funicona con contraeñas PPP /|\|

                //if (data is DateTime)
                //{
                //    return Convert.ToDateTime(temp);
                //}
                //if (data is Int32)
                //{
                //    return Convert.ToInt32(temp);
                //}
                
                return (T)temp;
            }
            else
            {
                return default(T);
            }
        }
        
        public static bool ValidateRut(this string rut)
        {
            Regex valid = new Regex(@"^0*(\d{1,3}(\.?\d{3})*)\-?([\dkK])$", RegexOptions.IgnoreCase);
            if (!string.IsNullOrWhiteSpace(rut) && valid.IsMatch(rut) && rut.Length >= 1 && rut.Length <= 9)
            {
                string body = rut.Substring(0, rut.Length - 1);
                string digit = rut.Substring(rut.Length - 1, 1);

                int numberRut = 0;
                if (int.TryParse(body, out numberRut))
                {
                    if (CheckDigit(numberRut).ToUpper() == digit.ToUpper())
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        public static bool ValidateText(this string text, byte length)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"^([a-zA-ZÑñ_áéíóú0-9\s]+)$", RegexOptions.None);
                if (valid.IsMatch(text) && text.Length <= length)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool ValidateDate(this DateTime date)
        {
            string text = date.ToShortDateString();
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"^([0][1-9]|[12][0-9]|3[01])(/|-)(0[1-9]|1[012])\2(\d{4})$", RegexOptions.IgnoreCase);
                if (valid.IsMatch(text))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool ValidateHour(this string hour)
        {
            if (!string.IsNullOrWhiteSpace(hour))
            {
                Regex valid = new Regex(@"^([0-1][0-9]|[2][0-3]):([0-5][0-9])$", RegexOptions.IgnoreCase);
                if (valid.IsMatch(hour))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool ValidateMail(this string text, byte length)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"(^[0-9a-zA-Z]+(?:[._][0-9a-zA-Z]+)*)@([0-9a-zA-Z]+(?:[._-][0-9a-zA-Z]+)*\.[0-9a-zA-Z]{2,3})$", RegexOptions.None);
                if (valid.IsMatch(text) && text.Length <= length)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool ValidateAddress(this string text, byte length)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"^[a-zA-ZÑñ.0-9\s#]*$", RegexOptions.None);
                if (valid.IsMatch(text) && text.Length <= length)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool ValidateTelephone(this string text, byte length)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"^(?:\+|-)?\d+$", RegexOptions.None);
                if (valid.IsMatch(text) && text.Length <= length)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool ValidatePassword(this string text)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"^[a-zA-ZñÑ0-9\s@#._-]*$", RegexOptions.None);
                if (valid.IsMatch(text) && text.Length <= 15)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Validate the password entered by the user 
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool ValidateNewPassword(this string text)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$", RegexOptions.None);
                if (valid.IsMatch(text) && text.Length >= 8 && text.Length <= 15)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool ValidateRegion(this string text, byte length)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"^([a-zA-ZÑñáéíóú\s]+)$", RegexOptions.None);
                if (valid.IsMatch(text) && text.Length <= length)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool ValidatePicture(this HttpPostedFile picture)
        {
            bool response = false;
            if (picture.ContentLength > 0)
            {
                if (picture.ContentType == "image/jpeg" || picture.ContentType == "image/pjpeg" || picture.ContentType == "image/jpg")
                {
                    BinaryReader b = new BinaryReader(picture.InputStream);
                    byte[] binData = b.ReadBytes((int)picture.InputStream.Length);
                    if (IsPicture(binData))
                    {
                        response = true;
                    }
                }
            }
            return response;
        }

        public static bool ValidatePicture(this FileUpload picture)
        {
            bool response = false;
            if (picture.FileContent.Length > 0)
            {
                if (picture.PostedFile.ContentType == "image/jpeg" || picture.PostedFile.ContentType == "image/pjpeg" || picture.PostedFile.ContentType == "image/jpg")
                {
                    if (IsPicture(picture.FileBytes))
                    {
                        response = true;
                    }
                }
            }
            return response;
        }

        private static bool IsPicture(byte[] data)
        {
            string bt = Encoding.ASCII.GetString(data).Substring(0, 16);
            if (bt.Substring(8, 2).ToString().ToLower() != "if")
            {
                if (bt.Substring(0, 3).ToString().ToLower() != "gif")
                {
                    if (bt.Substring(0, 2).ToString().ToLower() != "bm")
                    {
                        if (bt.Substring(0, 2).ToString().ToLower() != "ii")
                        {
                            bt = null;
                            return false;
                        }
                    }
                }
            }
            bt = null;
            return true;
        }

        public static bool IsNumber(this string text)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                Regex valid = new Regex(@"^[0-9]+$", RegexOptions.None);
                if (valid.IsMatch(text) && Convert.ToInt32(text) <= Int32.MaxValue)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static bool IsNumber(this int text)
        {
            string tempTexto = text.ToString();
            if (!string.IsNullOrWhiteSpace(tempTexto))
            {
                Regex valid = new Regex(@"^[0-9]+$", RegexOptions.None);
                if (valid.IsMatch(tempTexto) && Convert.ToInt32(text) <= Int32.MaxValue)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static string EncodeHtml(this string text)
        {
            return AntiXss.HtmlEncode(text);
        }
    }
}


